package com.geek.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.water.entity.Customer;
import com.geek.water.entity.Site;
import com.geek.water.exception.WaterException;
import com.geek.water.mapper.CustomerMapper;
import com.geek.water.service.CustomerService;
import com.geek.water.service.SiteService;
import com.geek.water.vo.PageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/7/28
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Autowired
    @Lazy  // 添加 @Lazy 注解
    private SiteService siteService;


    @Override
    public Page<Customer> listCustomers(PageQueryVO queryVO) {
        Page<Customer> page = Page.of(
                queryVO.getCurrentPage() != null ? queryVO.getCurrentPage() : 1,
                queryVO.getPageSize() != null ? queryVO.getPageSize() : 10
        );

        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(queryVO.getQueryString())) {
            wrapper.like(Customer::getName, queryVO.getQueryString())
                    .or()
                    .like(Customer::getCreditCode, queryVO.getQueryString());
        }
        if (queryVO.getStatus() != null) {
            wrapper.eq(Customer::getStatus, queryVO.getStatus());
        }
        wrapper.orderByDesc(Customer::getCreatedAt);

        Page<Customer> resultPage = baseMapper.selectPage(page, wrapper);

        if (!CollectionUtils.isEmpty(resultPage.getRecords())) {
            loadCustomerSites(resultPage.getRecords());
        }

        return resultPage;
    }

    private void loadCustomerSites(List<Customer> customers) {
        List<Long> customerIds = customers.stream()
                .map(Customer::getId)
                .collect(Collectors.toList());

        List<Site> sites = siteService.lambdaQuery()
                .in(Site::getCustomerId, customerIds)
                .list();

        Map<Long, List<Site>> siteMap = sites.stream()
                .collect(Collectors.groupingBy(Site::getCustomerId));

        customers.forEach(customer ->
                customer.setSites(siteMap.getOrDefault(customer.getId(), Collections.emptyList()))
        );
    }

    @Transactional
    @Override
    public boolean deleteCustomerWithCheck(Long customerId) {
        // 检查是否有关联站点
        if (hasAssociatedSites(customerId)) {
            throw new WaterException("客户存在关联站点，无法删除");
        }
        return this.removeById(customerId);
    }

    private boolean hasAssociatedSites(Long customerId) {
        return siteService.lambdaQuery()
                .eq(Site::getCustomerId, customerId)
                .count() > 0;
    }

    @Override
    public List<Site> getCustomerSites(Long customerId) {
        return siteService.lambdaQuery()
                .eq(Site::getCustomerId, customerId)
                .list();
    }
}
